﻿namespace Ficharts.Net
{
    #region 引用

    using System;
    using System.Collections;
    using System.Data;
    using System.Reflection;

    #endregion

    /// <summary>
    /// Data Source Parser
    /// </summary>
    public class DataSourceParser
    {
        #region Properties

        internal string DataTextField { get; set; }

        internal string DataValueField { get; set; }

        #endregion

        #region Methods

        internal DataTable Parse(object dataSource)
        {
            if (dataSource is DataTable)
            {
                return this.Parse((DataTable)dataSource);
            }
            if (dataSource is IList)
            {
                return this.Parse((IList)dataSource);
            }

            throw new ArgumentException("数据源必须为DataTable或者继承自IList.");
        }

        private DataTable Parse(DataTable dataTable)
        {
            return dataTable;
        }

        /// <summary>
        ///   Ilist<T>转换成 DataSet
        /// </summary>
        /// <param name="list"> </param>
        /// <returns> </returns>
        private DataTable Parse(IList list)
        {
            if (list == null || list.Count <= 0)
            {
                return null;
            }

            DataTable dt = new DataTable();

            foreach (object t in list)
            {
                DataRow row = dt.NewRow();

                PropertyInfo[] myPropertyInfo = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

                for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    PropertyInfo pi = myPropertyInfo[i];

                    string name = pi.Name;

                    if (dt.Columns[name] == null)
                    {
                        Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        var column = new DataColumn(name, colType);
                        dt.Columns.Add(column);
                    }

                    row[name] = pi.GetValue(t, null);
                }

                dt.Rows.Add(row);
            }

            return dt;
        }

        #endregion
    }
}